<template>
  <div id="layerManager" class="layerContent">
    <span class="corner" />
    <span class="corner" />
    <span class="corner" id="cornerLeft " />
    <span class="corner" id="cornerRight" />
    <div id="moveElement" class="coverage-title">
      <span>图层列表</span>
      <i
        class="el-icon-close"
        style="color: #fff"
        @click="coverageVisableFun"
      />
    </div>
    <div class="coverage-tree-content">
      <div class="tree-search">
        <input
          v-model="filterVal"
          type="text"
          placeholder="请输入名称过滤"
          class="search_input"
        />
        <!-- <i
          class="el-icon-search search_icon"
          style="color: #fff; font-size: 14px; cursor: pointer"
          @click="handleIconClick"
        /> -->
      </div>
      <div class="tree-content" id="tree-content">
        <el-tree
          ref="treeCover"
          class="layertree"
          :data="treeData"
          show-checkbox
          :default-expanded-keys="defaultExpandedKeys"
          node-key="id"
          :filter-node-method="filterNode"
          :props="defaultProps"
          @check="handleCheckChange"
          @node-click="clickNode"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span
                class="tree-label"
                :class="[data.layerTreeDTOList ? 'font-bold' : '']"
              >
                {{ data.name }}
              </span>
            </span>
          </template>
        </el-tree>
      </div>
      <div class="WideningRigth" id="WideningRigth"></div>
    </div>

    <div class="select-coverage-content">
      <div class="coverage-select-title" @click="expandSelected('basemap')">
        <span>已选底图</span>
        <i
          :class="{
            'el-icon-arrow-up': !isExpandBaseMap,
            'el-icon-arrow-down': isExpandBaseMap,
          }"
        />
      </div>
      <div class="select-vessel" v-show="isExpandBaseMap">
        <draggable
          v-model="selectBaseMapList"
          animation="1000"
          @end="baseMapDraggerEnd"
        >
          <div
            v-for="(item, index) in selectBaseMapList"
            v-show="item.isShow"
            :key="index"
            class="coverage-list"
            :class="{ 'select-row': item.isSelect }"
          >
            <div class="coverage-top" @click="selectFun(item, 'basemap')">
              <div class="coverage-left">
                <img src="./other/image/drag_icon.png" />
                <span>{{ item.name }}</span>
              </div>
            </div>
            <!-- v-if="item.isSelect" -->
            <div v-if="item.isSelect" class="solide-content">
              <div class="solide-left">
                <p>透明度</p>

                <el-popover placement="bottom-end" width="100" trigger="hover">
                  <el-slider
                    v-model="item.clarity"
                    :min="0"
                    :max="100"
                    :step="1"
                    :show-tooltip="false"
                    @change="changeLayerClarity(item, 'basemap')"
                  />
                  <div slot="reference" class="value-content">
                    <span>{{ item.clarity }}%</span>
                    <i class="el-icon-arrow-down" />
                  </div>
                </el-popover>
              </div>
              <i
                class="el-icon-delete"
                style="color: #fff; font-size: 18px"
                @click="removeLayer(item, 'basemap')"
              />
            </div>
          </div>
        </draggable>
      </div>
    </div>
    <div class="select-coverage-content">
      <div class="coverage-select-title" @click="expandSelected('2d')">
        <span>已选矢量图层（二维）</span>
        <i
          :class="{
            'el-icon-arrow-up': !isExpand2d,
            'el-icon-arrow-down': isExpand2d,
          }"
        />
      </div>
      <div class="select-vessel" v-show="isExpand2d">
        <draggable
          v-model="selectVectorList"
          animation="1000"
          @end="VDraggerEnd"
        >
          <div
            v-for="(item, index) in selectVectorList"
            v-show="item.isShow"
            :key="index"
            class="coverage-list"
            :class="{ 'select-row': item.isSelect }"
          >
            <div class="coverage-top" @click="selectFun(item, '2d')">
              <div class="coverage-left">
                <img src="./other/image/drag_icon.png" />
                <span>{{ item.name }}</span>
              </div>
            </div>
            <!-- v-if="item.isSelect" -->
            <div v-if="item.isSelect" class="solide-content">
              <div class="solide-left">
                <p>透明度</p>

                <el-popover placement="bottom-end" width="100" trigger="hover">
                  <el-slider
                    v-model="item.clarity"
                    :min="0"
                    :max="100"
                    :step="1"
                    :show-tooltip="false"
                    @change="changeLayerClarity(item, '2d')"
                  />
                  <div slot="reference" class="value-content">
                    <span>{{ item.clarity }}%</span>
                    <i class="el-icon-arrow-down" />
                  </div>
                </el-popover>
              </div>
              <i
                class="el-icon-delete"
                style="color: #fff; font-size: 18px"
                @click="removeLayer(item, '2d')"
              />
            </div>
          </div>
        </draggable>
      </div>
    </div>
    <div class="select-coverage-content">
      <div class="coverage-select-title" @click="expandSelected('3d')">
        <span>已选图层（三维）</span>
        <i
          :class="{
            'el-icon-arrow-up': !isExpand3d,
            'el-icon-arrow-down': isExpand3d,
          }"
        />
      </div>
      <div class="select-vessel" v-show="isExpand3d">
        <div
          v-for="(item, index) in select3dLayers"
          v-show="item.isShow"
          :key="index"
          class="coverage-list"
          :class="{ 'select-row': item.isSelect }"
        >
          <div class="coverage-top" @click="selectFun(item, '3d')">
            <div class="coverage-left">
              <span>{{ item.name }}</span>
            </div>
          </div>
          <!-- v-if="item.isSelect" -->
          <div v-if="item.isSelect" class="solide-content">
            <div class="solide-left">
              <p>透明度</p>

              <el-popover placement="bottom-end" width="100" trigger="hover">
                <el-slider
                  v-model="item.clarity"
                  :min="0"
                  :max="100"
                  :step="1"
                  :show-tooltip="false"
                  @change="changeLayerClarity(item, '3d')"
                />
                <div slot="reference" class="value-content">
                  <span>{{ item.clarity }}%</span>
                  <i class="el-icon-arrow-down" />
                </div>
              </el-popover>
            </div>
            <i
              class="el-icon-delete"
              style="color: #fff; font-size: 18px"
              @click="removeLayer(item, '3d')"
            />
          </div>
        </div>
      </div>
    </div>
    <div class="WideningBottom" id="WideningBottom"></div>
  </div>
</template>

<script>
/* eslint-disable */
import draggable from "vuedraggable";
import { changeEl } from "./other/draggingElement";
import layerManager from "./util/layerManager";
export default {
  props: {
    treeData: {
      type: Array,
      default: [],
    },
  },
  data() {
    return {
      defaultProps: {
        children: "layerTreeDTOList",
        label: "name",
      },
      defaultExpandedKeys: [],
      selectVectorList: [],
      selectBaseMapList: [],
      select3dLayers: [],
      sortIds: [],
      filterVal: "",
      layerVisible: false,
      coverageVisable: false,
      addedLayers: [],
      willAddLayer: [], //将要加载的图层
      isExpand2d: false,
      isExpand3d: false,
      isExpandBaseMap: false,
    };
  },
  components: { draggable },
  watch: {
    filterVal(val) {
      this.$refs.treeCover.filter(val);
    },
  },
  created() {
    this.getLayerData();
  },
  mounted() {
    changeEl.Dragging("layerManager");
  },
  beforeDestroy() {
    this.$store.commit("updateWMTSLayers", { isInit: true });
    this.$store.commit("updateTilesLayers", { isInit: true });
    this.$store.commit("updateVectorLayers", { isInit: true });
    this.$store.commit("updateXYZLayers", { isInit: true });
    this.$store.commit("updateWMSLayers", { isInit: true });
  },
  methods: {
    showLayerContent() {
      this.layerVisible = true;
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    getLayerData() {
      this.defaultExpandedKeys = [];
      this.treeData.forEach((item) => {
        this.defaultExpandedKeys.push(item.id);
      });
    },
    coverageVisableFun() {
      this.$parent.layerStyle = "animate__animated animate__fadeOutLeft";
      changeEl.removeDown();
    },
    enter() {
      this.$parent.layerStyle = "animate__animated animate__fadeInLeft";
      this.$nextTick(() => {
        // changeEl.scaleing("cornerRight");
        changeEl.changeWidth("WideningRigth");
        changeEl.changeHeigth("WideningBottom");
      });
    },
    async handleCheckChange(d, state) {
      this.willAddLayer = [];
      if (d.layerTreeDTOList) {
        d.layerTreeDTOList.forEach((item) => {
          this.getLayerObj(item);
        });
      } else {
        this.willAddLayer.push(d);
      }
      this.willAddLayer.forEach((item) => {
        let checked = this.$refs.treeCover.getNode(item.id).checked;
        if (item.type == "3dTiles") {
          let l = this.$store.state.layerManager.tilesLayers.filter(
            (s) => item.id == s.id
          );
          if (l.length) {
            this.select3dLayers.forEach((e) => {
              if (e.id == l[0].id) {
                e.isShow = checked;
              }
            });
            scene.primitives._primitives[l[0].layerIndex].show = checked;
            l[0].status = checked;
            this.$store.commit("updateTilesLayers", l[0]);
          } else {
            let layer = layerManager.add3dTiles(item);
            this.addedLayers.push({ layer, id: item.id });
            this.select3dLayers.unshift({
              ...item,
              isSelect: false,
              isShow: true,
              clarity: 100,
            });
          }
        } else if (item.type == "geojson") {
          let l = this.$store.state.layerManager.vectorLayers.filter(
            (s) => item.id == s.id
          );
          if (l.length) {
            this.selectVectorList.forEach((e) => {
              if (e.id == l[0].id) {
                e.isShow = checked;
              }
            });
            viewer.dataSources.getByName(l[0].name)[0].show = checked;
            l[0].status = checked;
            this.$store.commit("updateVectorLayers", l[0]);
          } else {
            let layer = layerManager.addGeoJson(item);
            this.addedLayers.push({ layer, id: item.id });
            this.selectVectorList.unshift({
              //新添加的geojson图层跟栅格底图不一样，添加在最上层
              ...item,
              isSelect: false,
              isShow: true,
              clarity: 100,
            });
          }
        } else if (item.type == "wmts") {
          let l = this.$store.state.layerManager.wmtsLayers.filter(
            (s) => item.id == s.id
          );
          if (l.length) {
            this.selectBaseMapList.forEach((e) => {
              if (e.id == l[0].id) {
                  e.isShow = checked;
              }
            });
            viewer.imageryLayers._layers[l[0].layerIndex].show = checked;
            l[0].status = checked;
            this.$store.commit("updateWMSLayers", l[0]);
          } else {
            let layer = layerManager.addWMTS(item);
            this.addedLayers.push({ layer, id: item.id });
            this.selectBaseMapList.push({
              ...item,
              isSelect: false,
              isShow: true,
              clarity: 100,
            });
          }
        }
      });
    },
    selectFun(row, engine) {
      if (engine == "basemap") {
        this.selectBaseMapList.forEach((item) => {
          if (item.id == row.id) {
            item.isSelect = !item.isSelect;
          } else {
            item.isSelect = false;
          }
        });
      } else if (engine == "2d") {
        this.selectVectorList.forEach((item) => {
          if (item.id == row.id) {
            item.isSelect = !item.isSelect;
          } else {
            item.isSelect = false;
          }
        });
      } else {
        this.select3dLayers.forEach((item) => {
          if (item.id == row.id) {
            item.isSelect = !item.isSelect;
          } else {
            item.isSelect = false;
          }
        });
      }
    },
    changeLayerClarity(item, type) {
      let alpha = item.clarity / 100;
      if (type == "2d") {
        let urlArr = item.url.split("/");
        let layerName = urlArr[urlArr.length - 1];
        let layerEntities =
          viewer.dataSources.getByName(layerName)[0].entities.values;
        for (var i = 0; i < layerEntities.length; i++) {
          var entity = layerEntities[i];
          let color = Cesium.Color.fromRandom({
            ...entity.polygon.material.getValue().color,
            alpha,
          });
          entity.polygon.material = color;
        }
      } else if (type == "basemap") {
        let l = this.$store.state.layerManager.wmtsLayers.filter(
          (s) => item.id == s.id
        );
        if (l.length) {
          viewer.imageryLayers._layers[l[0].layerIndex].alpha = alpha;
        }
      } else {
        let l = this.$store.state.layerManager.tilesLayers.filter(
          (s) => item.id == s.id
        );
        if (l.length) {
          scene.primitives._primitives[l[0].layerIndex].style =
            new Cesium.Cesium3DTileStyle({
              color: "color('rgba(255,255,255," + alpha + ")')",
            });
        }
      }
    },
    VDraggerEnd(moved) {
      if (moved.newIndex == moved.oldIndex) return; //如果位置没变化则不执行下面代码
      let temp = moved.oldIndex - moved.newIndex;
      let l = this.selectVectorList[moved.newIndex];
      let layerEntities = this.getGeojsonLayer(l.url).entities.values;
      layerEntities.forEach((item) => {
        item.polygon.perPositionHeight = false;
        item.polygon.height._value += 0.7 * temp;
        item.polygon.outline = false;
      });
      if (temp > 0) {
        for (let i = 1; i <= temp; i++) {
          let lowL = this.selectVectorList[moved.newIndex + i];
          let lowLayerEntities = this.getGeojsonLayer(lowL.url).entities.values;
          lowLayerEntities.forEach((item) => {
            item.polygon.perPositionHeight = false;
            item.polygon.height._value -= 0.7;
            item.polygon.outline = false;
          });
        }
      } else {
        for (let i = 1; i <= -temp; i++) {
          let lowL = this.selectVectorList[moved.newIndex - i];
          let lowLayerEntities = this.getGeojsonLayer(lowL.url).entities.values;
          lowLayerEntities.forEach((item) => {
            item.polygon.perPositionHeight = false;
            item.polygon.height._value += 0.7;
            item.polygon.outline = false;
          });
        }
      }
    },
    baseMapDraggerEnd(moved) {
      let temp = moved.oldIndex - moved.newIndex; //计算图层提升了几个层级，大于零表示拖动的图层层级变大，向上显示
      let ml = this.selectBaseMapList[moved.newIndex];
      let l = this.$store.state.layerManager.wmtsLayers.filter(
        (s) => ml.id == s.id
      );
      let moveLayer = viewer.imageryLayers._layers[l[0].layerIndex];
      if (temp == 0) {
        return;
      } else if (temp > 0) {
        for (let i = 1; i <= temp; i++) {
          viewer.imageryLayers.raise(moveLayer);
          let ml1 = this.selectBaseMapList[moved.newIndex + i];
          let l1 = this.$store.state.layerManager.wmtsLayers.filter(
            (s) => ml1.id == s.id
          );
          l1[0].layerIndex = l1[0].layerIndex - 1;
          this.$store.commit("updateWMSLayers", l1[0]);
        }
      } else {
        for (let i = 1; i <= -temp; i++) {
          viewer.imageryLayers.lower(moveLayer);
          let ml1 = this.selectBaseMapList[moved.newIndex - i];
          let l1 = this.$store.state.layerManager.wmtsLayers.filter(
            (s) => ml1.id == s.id
          );
          l1[0].layerIndex = l1[0].layerIndex + 1;
          this.$store.commit("updateWMSLayers", l1[0]);
        }
      }
      l[0].layerIndex = l[0].layerIndex + temp;
      this.$store.commit("updateWMSLayers", l[0]);
    },
    getLayerObj(datas) {
      if (datas.layerTreeDTOList) {
        datas.layerTreeDTOList.forEach((item) => {
          this.getLayerObj(item);
        });
      } else {
        this.willAddLayer.push(datas);
      }
    },
    clickNode(d, n) {
      if (d.layerTreeDTOList || !n.checked) return;
      let l = this.addedLayers.filter((l) => l.id == d.id);
      viewer.flyTo(l[0].layer);
    },
    expandSelected(e) {
      if (e == "2d") {
        this.isExpand2d = !this.isExpand2d;
      } else if (e == "basemap") {
        this.isExpandBaseMap = !this.isExpandBaseMap;
      } else {
        this.isExpand3d = !this.isExpand3d;
      }
    },
    getGeojsonLayer(url) {
      let urlArr = url.split("/");
      let layerName = urlArr[urlArr.length - 1];
      let layer = viewer.dataSources.getByName(layerName)[0];
      return layer;
    },
    removeLayer(item, type) {
      if (type == "2d") {
        let l = this.$store.state.layerManager.vectorLayers.filter(
          (s) => item.id == s.id
        );
        if (l.length) {
          this.selectVectorList.forEach((e) => {
            if (e.id == l[0].id) {
              if (l[0].status) {
                e.isShow = false;
              } else {
                e.isShow = true;
              }
            }
          });
          viewer.dataSources.getByName(l[0].name)[0].show = !l[0].status;
          l[0].status = !l[0].status;
          this.$store.commit("updateVectorLayers", l[0]);
        }
      } else if (type == "basemap") {
        let l = this.$store.state.layerManager.wmtsLayers.filter(
          (s) => item.id == s.id
        );
        if (l.length) {
          this.selectBaseMapList.forEach((e) => {
            if (e.id == l[0].id) {
              if (l[0].status) {
                e.isShow = false;
              } else {
                e.isShow = true;
              }
            }
          });
          viewer.imageryLayers._layers[l[0].layerIndex].show = !l[0].status;
          l[0].status = !l[0].status;
          this.$store.commit("updateWMSLayers", l[0]);
        }
      } else {
        let l = this.$store.state.layerManager.tilesLayers.filter(
          (s) => item.id == s.id
        );
        if (l.length) {
          this.select3dLayers.forEach((e) => {
            if (e.id == l[0].id) {
              if (l[0].status) {
                e.isShow = false;
              } else {
                e.isShow = true;
              }
            }
          });
          scene.primitives._primitives[l[0].layerIndex].show = !l[0].status;
          l[0].status = !l[0].status;
          this.$store.commit("updateTilesLayers", l[0]);
        }
      }
      this.$refs.treeCover.setChecked(item.id, false);
    },
  },
};
</script>

<style lang="scss" scoped>
.layerContent {
  .WideningBottom {
    height: 20px;
    width: 97%;
    background-color: transparent;
    cursor: row-resize;
    position: absolute;
    left: 0px;
    bottom: -10px;
  }
  position: absolute;
  left: 130px;
  top: 70px;
  width: 229px;
  height: auto;
  background: rgba($color: #1e2a3d, $alpha: 0.5);
  border: 1px solid #348da6;
  .corner {
    position: absolute;
    width: 13px;
    height: 13px;
  }
  .corner:nth-child(1) {
    height: 3px;
    background-color: #2c98ca;
    top: 0;
    left: 0;
  }
  .corner:nth-child(2) {
    height: 3px;
    background-color: #2c98ca;
    top: 0;
    right: 0;
  }
  .corner:nth-child(3) {
    bottom: 0;
    left: 0;
    border: 2px solid #ffffff;
    border-top: none;
    border-right: none;
  }
  .corner:nth-child(4) {
    bottom: 0;
    right: 0;
    border: 2px solid #ffffff;
    border-top: none;
    border-left: none;
  }
}
.coverage-title {
  height: 40px;
  cursor: all-scroll;

  border: 1px solid rgba(52, 141, 166, 0.56);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  font-size: 16px;
  span {
    font-weight: bold;
    color: #fff;
  }

  i {
    color: #aaaaaa;
    cursor: pointer;
  }
}

.coverage-tree-content {
  position: relative;
  .WideningRigth {
    height: 100%;
    width: 10px;
    background-color: transparent;
    cursor: col-resize;
    position: absolute;
    right: -5px;
    top: 0px;
  }
  .tree-search {
    width: 100%;
    margin-top: 20px;
    position: relative;
    display: flex;
    justify-content: center;
    .search_input {
      width: 100%;
      height: 30px;
      outline: none;
      border: 1px solid #2c98ca;
      border-radius: 5px;
      font-size: 14px;
      background: rgba($color: #283344, $alpha: 0.2);
      padding: 0 40px 0 10px;
      color: #fff;
    }
    .search_input::-webkit-input-placeholder {
      // 这里写placeholder的样式

      color: #999999;
    }
    .search_icon {
      position: absolute;
      right: 22px;
      top: 50%;
      transform: translateY(-50%);
    }
  }

  .tree-content {
    margin-top: 20px;
    max-height: 350px;
    overflow-y: auto;
    display: flex;
    .layertree {
      background: transparent;
      width: 100%;
    }
    .tree-label {
      display: inline-block;
      height: 36px;
      line-height: 36px;
      font-size: 14px;
      color: #fff;
    }

    .font-bold {
      font-weight: bold;
    }
  }
}

.select-coverage-content {
  .coverage-select-title {
    height: 40px;
    // background: #eeeeee;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
    font-size: 16px;
    cursor: pointer;
    span {
      font-weight: bold;
      color: #fff;
    }

    i {
      color: #fff;
      cursor: pointer;
    }
  }
  .select-vessel {
    max-height: 100px;
    overflow-y: auto;
    // font-size: 14px;
    .coverage-list {
      cursor: pointer;
      .coverage-top {
        padding: 0 20px;
        height: 40px;
        display: flex;
        align-items: center;
        .coverage-left {
          height: 40px;
          display: flex;
          align-items: center;
          font-size: 14px;
          color: #fff;
          img {
            margin-right: 15px;
            height: 10px;
          }
        }
      }

      .solide-content {
        height: 50px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 20px;
        background: rgba($color: #2ba0cf, $alpha: 0.2);
        .solide-left {
          padding-left: 25px;
          display: flex;
          align-items: center;

          p {
            color: #fff;
            font-size: 12px;
            padding-right: 5px;
          }

          .value-content {
            width: 74px;
            height: 26px;
            background: rgba($color: #2ba0cf, $alpha: 0.5);
            font-size: 14px;

            color: #fff;
            align-items: center;
            justify-content: center;
            display: flex;

            i {
              padding-left: 5px;
            }
          }
        }

        .del-right {
          color: #aaaaaa;
        }
      }
    }

    .select-row {
      background: rgba(32, 132, 254, 0.06);
    }
  }
}

::v-deep .is-current {
  background-color: rgba($color: #2ba0cf, $alpha: 0.2) !important;
}
::v-deep
  .el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content {
  background-color: transparent;
}
::v-deep .el-tree-node__content:hover {
  background-color: rgba($color: #2ba0cf, $alpha: 0.2) !important;
}
/* 滑道样式  设置透明 */
.tree-content::-webkit-scrollbar-track,
.select-vessel::-webkit-scrollbar-track {
  background-color: transparent;
  // border-radius: 7px;
}

/* 滑块样式 */
.tree-content::-webkit-scrollbar-thumb,
.select-vessel::-webkit-scrollbar-thumb {
  background-color: #2ba0cf;
  border-radius: 1px;
  // border: 1px solid #f4f4f4;
}

/* 滚动条宽度 */
.tree-content::-webkit-scrollbar,
.select-vessel::-webkit-scrollbar {
  width: 3px;
  height: 5px;
}

/* 滚动条拐角 */
// .tree-content::-webkit-scrollbar-corner {
//   background-color: #f4f4f4;
// }
::v-deep .el-tree-node:focus > .el-tree-node__content {
  background-color: rgba($color: #2ba0cf, $alpha: 0.2) !important;
}
</style>
